﻿using Microsoft.Extensions.Logging;
using MiniCap.Abstractions;
using MiniCap.Storage;
using MySqlConnector;
using System.Text.Json;

namespace MiniCap.Core
{
    public class MiniCapPublisher : IMiniCapPublisher
    {
        private readonly MySqlOutboxStorage _storage;
        private readonly ILogger<MiniCapPublisher> _logger;

        public MiniCapPublisher(MySqlOutboxStorage storage, ILogger<MiniCapPublisher> logger)
        {
            _storage = storage;
            _logger = logger;
        }

        public async Task PublishAsync(string topic, object? payload, IDictionary<string, string>? headers = null, CancellationToken ct = default)
        {
            var content = JsonSerializer.Serialize(payload);

            await using var conn = _storage.CreateConnection();
            await conn.OpenAsync(ct);
            await using var tran = await conn.BeginTransactionAsync(ct);

            await _storage.AddOutboxAsync(conn, tran, topic, content, headers);

            await tran.CommitAsync(ct);

            _logger.LogInformation("Published message to outbox: {Topic}", topic);
        }

        public async Task PublishAsync(MySqlConnection conn, MySqlTransaction tran, string topic, object? payload, IDictionary<string, string>? headers = null, CancellationToken ct = default)
        {
            var content = JsonSerializer.Serialize(payload);
            await _storage.AddOutboxAsync(conn, tran, topic, content, headers);
        }
    }
}
